#include "abf_util.h"

#include "abf_flat.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void* abf_alloc(const char* function, unsigned needed)
{
    void *memory = malloc(needed);
    if (memory==0)
    {
        fprintf (stderr, "*** %s: failed to allocate %d more bytes.\n", function, needed);
        abort();
    }
    return memory;
}

void* abf_realloc(const char* function, void* data, unsigned have, unsigned needed)
{
    void *memory = 0;
    if (have==0)
        return abf_alloc(function, needed);
    memory = realloc(data, needed);
    if (memory)
        return memory;
    memory = abf_alloc(function, needed);
    memcpy(memory,data,have);
    return memory;
}

int abf_read_into (const char* filename, char** buffer, uint32_t* capacity, uint32_t* size)
{
    uint32_t chunk_size = 5*1024;
    uint32_t bytes;
    char* ptr;
    FILE* file = fopen (filename,"r");
    if (!file)
        return ABF_E_CANNOT_READ;

    *buffer = (char*) CHECKED_ALLOC(chunk_size);
    *capacity = chunk_size;
    *size = 0;
    ptr = *buffer;

    while (!feof(file) && !ferror(file))
    {
        if (*capacity < *size + chunk_size)
        {
            *buffer = (char*) CHECKED_REALLOC(*buffer,*capacity,*capacity + chunk_size);
            *capacity = *capacity + chunk_size;
        }
        bytes = fread (ptr, 1, chunk_size, file);
        ptr += bytes;
        *size += bytes;
    }
    fclose (file);
    return ABF_OK;
}